const { Controller } = require('egg');
const responseMid = require('../middleware/response');

/**
 * 根据fuid、生成的内容生成二维码链接
 */
class GenerateQrcodeController extends Controller {
  async create() {
    const { ctx, service } = this;
    const { fuid, content } = ctx.request.body;

    if (!fuid || !content) {
      ctx.body = responseMid.fail(500, 'fuid or content is required');
      return;
    }

    const stamp = this.generateUUID();
    const createResult = await service.generateQrcode.createOrUpdate({ fuid, content, stamp });

    if (createResult.id) {
      const link = `${ctx.origin}/qrcode/${stamp}`; // 注意，这取决于你的路由如何定义
      ctx.body = responseMid.success({
        qrcodeLink: link,
      });
    } else {
      ctx.body = responseMid.fail(500, 'generateQrcode createOrUpdate error');
    }
  }
  generateUUID() {
    let result = '';
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const charactersLength = characters.length;
    for (let i = 0; i < 20; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    result = result.replace(/(.{4})(.{4})(.{4})(.{8})/, '$1-$2-$3-$4');
    return result;
  }
}

module.exports = GenerateQrcodeController;
